import React, { useState, useRef, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import { PullToRefresh, VirtualList, InfiniteScroll, NavBar, Image, Tag, Icon, Button, Row, Col, Tab, Tabs, ActionSheet, Rate, Toast } from '@antmjs/vantui';
import Taro, { getMenuButtonBoundingClientRect, eventCenter,useShareAppMessage } from '@tarojs/taro';
import { IconFont } from '../../../../components';
import { CusCard, CusSroll } from '../../../../components'
import { Getappdetail, Getapphistory, makecore, getScorelog, appcollection } from '../../../../https/home'
import { HOST, diffTime, getUserInfo, judgeLogin } from '../../../../utils/const'
import './index.scss'

const pla = { android: "安卓", ios: "苹果", windows: "windows", mac: 'mac' }
const Toast_ = Toast.createOnlyToast()

export default function AppVersionList() {

    const bar = getMenuButtonBoundingClientRect()
    const [data, setData] = useState([]);
    const infiniteScrollRef = useRef();
    const virtualListRef = useRef();
    const [show, setShow] = useState(false)
    const [coins, setCoins] = useState([1, 2, 6, 7, 66, 88, 99])
    const [selectIndex, setSelectIndex] = useState(1)
    const [fractionShow, setFractionShow] = useState(false)
    const [fractionVal, setFractionVal] = useState(0.1)
    const [detailInfo, setDetailInfo] = useState(null)
    const [coreList, setCoreList] = useState([])
    const [isCollection, setIsCollection] = useState(false)
    const [hisListData, setHisListData] = useState([])

    //获取当前路由参数
    const instance = Taro.getCurrentInstance().router.params

    useEffect(() => {
        getDetailInfo()
    }, [])

    //获取应用详情
    const getDetailInfo = () => {
        Taro.showLoading({ title: '加载中' })
        Getappdetail(instance?.id, instance?.version).then((res) => {
            Taro.hideLoading()
            if (res.success) {
                setDetailInfo(res?.data)
            }
        })
    }

    useShareAppMessage((res) => {
        if (res.from === "button") {
          // 来自页面内分享按钮
        } else {
          // 右上角分享好友
        }
    
        return {
          title: "", // 分享卡片的title
          path: "", // 分享卡片的小程序路径
          imageUrl: "", // 分享卡片的图片链接
        };
      });

    //获取应用历史版本记录
    const getHistoryData = () => {
        Taro.showLoading({ title: '加载中' })
        Getapphistory(instance?.id, instance?.version).then((res) => {
            Taro.hideLoading()
            if (res.success) {
                setHisListData(res.data)
            }
        })
    }

    const changeImgData = () => {
        let arr = JSON.parse(detailInfo.images);
        let newArr = arr.map((item) => {
            return HOST + item
        })
        return newArr
    }

    const subMitCore = () => {
        Taro.showLoading({ title: '加载中' })
        makecore({
            appId: instance?.id, version: instance?.version, score: fractionVal * 2,
            userId: getUserInfo()?.user_id
        }).then((res) => {
            Taro.hideLoading()
            if (res.success) {
                setFractionShow(false)
                Toast_.show('评分成功')
                getCoreList()
            }
        })
    }

    const getCoreList = () => {
        Taro.showLoading({ title: '加载中' })
        getScorelog({ appId: instance?.id, version: instance?.version }).then((res) => {
            Taro.hideLoading()
            if (res.success) {
                setCoreList(res?.data)
            }
        })
    }

    const changeAppcollection = () => {
        if (!judgeLogin()) {
            return Taro.showToast({ title: '请先登录', icon: 'error' })
        }
        Taro.showLoading({ title: '加载中' })
        appcollection({ appId: instance?.id, version: instance?.version, userId: getUserInfo()?.user_id, opType: isCollection ? 1 : 0 }).then((res) => {
            Taro.hideLoading()
            if (res.success) {
                setIsCollection(!isCollection)
                eventCenter.trigger("updateUserInfo", {
                    result: true,
                });
                if (!isCollection) {
                    Toast_.show('收藏成功')
                } else {
                    Toast_.show('取消收藏成功')
                }
            }
        })
    }

    const listData = (type) => {
        return (
            (
                <PullToRefresh>
                    <VirtualList
                        style={{ padding: 10, boxSizing: 'border-box' }}
                        height="calc(100vh - 135px)"
                        dataSource={type == 'score' ? coreList : hisListData}
                        showCount={3}
                        ref={virtualListRef}
                        // footer={
                        //     <InfiniteScroll
                        //         parentClassName="van-virtual-list"
                        //         loadMore={loadMore}
                        //         ref={infiniteScrollRef}
                        //     />
                        // }
                        ItemRender={({ item }) => {
                            if (type == 'version') {
                                return (
                                    <View className='list-bg-view' onClick={() => Taro.navigateTo({ url: `/pages/home/components/down_load_file/index?link=${detailInfo?.link}` })}>
                                        <View className='img'>
                                            <Image src={HOST + item?.icon} radius={'8%'} width={120} height={120} />
                                        </View>
                                        <View className='info-text'>
                                            <View>
                                                {item?.name || ''}
                                            </View>
                                            <View className='tag-view'>
                                                <Icon name="star" color="#13b858" size={40} />
                                                <Text className="star-text">{item?.core || ''}</Text>
                                                <View className='version-view'>{item?.version || ''}</View>
                                                <View className='version-view'>{item?.create_time ? diffTime(new Date(item?.create_time).getTime()) : '未知'}</View>
                                            </View>
                                            <View className='tag-view'>
                                                <Tag className='tag' type="primary">{item?.platform ? pla[item.platform] : ''}</Tag>
                                                <View className='version-view'>{item?.size || ""}</View>
                                                <View className='separate-veiw'>·</View>
                                                <View className='version-view'>{item?.downloadCnt || ''}</View>
                                            </View>
                                        </View>
                                        <View className='time-view'>
                                            <Button className='btn' type='primary' size='mini'>下载</Button>
                                        </View>
                                    </View>
                                );
                            } else {
                                return (
                                    <View className='list-bg-view'>
                                        <View className='img'>
                                            <Image src={item?.avatar ? HOST + item.avatar : 'https://img.yzcdn.cn/vant/cat.jpeg'} radius={'30px'} width={120} height={120} />
                                        </View>
                                        <View className='info-text'>
                                            <View>
                                                {item?.nickname || ''}
                                            </View>
                                            <View className='tag-view'>
                                                <Icon name="star" color="#13b858" size={40} />
                                                <Text className="star-text">{item?.score || ''}</Text>
                                                <View className='version-view'>{item?.create_time ? diffTime(new Date(item?.create_time).getTime()) : '未知'}</View>
                                                <View className='separate-veiw'>·</View>
                                                <View className='version-view'>评分</View>
                                            </View>
                                        </View>
                                    </View>
                                );
                            }
                        }}
                    />
                </PullToRefresh>
            )

        )
    }

    return (
        <View className='mycoins-frame-view'>
            <NavBar fixed title='应用详情' leftArrow leftText={'返回'} onClickLeft={() => Taro.navigateBack()} />
            <View className='list-bg-view' style={{ paddingTop: bar.bottom + 20 }}>
                <View className='img'>
                    <Image src={detailInfo ? HOST + detailInfo?.icon : ''} radius={'8%'} width={120} height={120} />
                </View>
                <View className='info-text'>
                    <View>
                        {detailInfo?.name || ''}
                    </View>
                    <View className='tag-view'>
                        {/* <Icon name="star" color="#13b858" size={40} /> */}
                        {/* <Text className="star-text">{detailInfo?.version||''}</Text> */}
                        <View className='version-view'>{detailInfo?.create_time ? diffTime(new Date(detailInfo?.create_time).getTime()) : '未知'}</View>
                    </View>
                    <View className='tag-view'>
                        <Tag className='tag' type="primary">{detailInfo?.platform ? pla[detailInfo.platform] : ''}</Tag>
                        <Tag className='tag' type="primary">{detailInfo?.size || ""}</Tag>
                        <Tag className='tag' type="primary">{detailInfo?.version || ""}</Tag>
                    </View>
                </View>
            </View>
            <Row className='row-bg-viw'>
                <Col span={7.33}>
                    <View className='col-view'>
                        <View className='row-view'>
                            <Icon name="star" color="#13b858" size={30} />
                            <Text >9.0</Text>
                        </View>
                        <View className='sub-tit'>180人打分</View>
                    </View>
                </Col>
                <Col span={1}>
                    <View className='line-view'></View>
                </Col>
                <Col span={7.33}>
                    <View className='col-view'>
                        <View>
                            {detailInfo?.size || ''}
                        </View>
                        <View className='sub-tit'>大小</View>
                    </View>
                </Col>
                <Col span={1}>
                    <View className='line-view'></View>
                </Col>
                <Col span={7.33}>
                    <View className='col-view'>
                        <View>
                            {`${detailInfo?.downloadCnt || 0}人`}
                        </View>
                        <View className='sub-tit'>下载</View>
                    </View>
                </Col>
                {/* <Col span={1}>
                    <View className='line-view'></View>
                </Col> */}
                {/* <Col span={5.25}>
                    <View className='col-view'>
                        <View className='row-view'>
                            <Text >5</Text>
                            <IconFont name="ac-jinbi2" size={35} />
                        </View>
                        <View className='sub-tit'>5人投币</View>
                    </View>
                </Col> */}
            </Row>
            <Tabs sticky={true} active={1} ellipsis={false} onChange={({ detail: { index, title } }) => {
                if (index == 1) {
                    getCoreList()
                } else if (index == 2) {
                    getHistoryData()
                }
            }}>
                <Tab title="详情" name="1" className='tab-bg-view'>
                    <View style={{ padding: '20px 0px' }}>
                        <CusSroll
                            type={'detail'} scrollWidth={detailInfo?.platform == 'ios' || detailInfo?.platform == 'android' ? 300 : 800}
                            list={(detailInfo?.images && JSON.parse(detailInfo.images)) || []}
                            onClick={(item) => {
                                Taro.previewImage({
                                    current: HOST + item,
                                    enablesavephoto: true,
                                    urls: changeImgData()
                                })
                            }}
                        />
                    </View>
                    <View className='warn-view'>该软件由用户上传，仅用于学习用途，请在下载后24小时内删除，
                        我们本着支持正版的原则，敬告所有用户，本站下载的软件，
                        不得应用于商业用途！
                    </View>
                    <View className='detail-info-view'>
                        <View className='header-view'>关于应用</View>
                        <View className='info-tit-view'>
                            {detailInfo?.desc || ''}
                        </View>
                    </View>

                </Tab>
                <Tab title="评分" name="2">
                    {listData('score')}
                </Tab>
                <Tab title="版本" name="3">
                    {listData('version')}
                </Tab>
            </Tabs>
            <View className='bottom-view'>
                <View className='btn-view' onClick={changeAppcollection}>
                    <Icon name={isCollection ? 'like' : 'like-o'} color={isCollection ? 'red' : ''} size={40} />
                    <View>收藏</View>
                </View>
                {/* <View className='btn-view' onClick={() => setShow(true)}>
                    <IconFont name="ac-jinbi2" size={40} />
                    <View>投币</View>
                </View> */}
                <View className='btn-view' onClick={() => {
                    if (!judgeLogin()) {
                        return Taro.showToast({ title: '请先登录', icon: 'error' })
                    }
                    setFractionShow(true)
                }}>
                    <Icon name='star-o' size={40} />
                    <View>评分</View>
                </View>
                <View onClick={() => Taro.navigateTo({ url: `/pages/home/components/down_load_file/index?link=${detailInfo?.link}` })} className='down-view'>
                    <View>下载</View>
                    <View className='size-tit'>{detailInfo?.size || ''}</View>
                </View>
            </View>
            <ActionSheet show={show} title="投币" onClose={() => setShow(false)}>
                <View className="sheet-view">
                    <View>请给应用投币（默认投一币）</View>
                    {coins.map((item, index) => {
                        return (
                            <View onClick={() => setSelectIndex(item)} className='sub-view' style={{ backgroundColor: selectIndex == item ? '#FEF9E8' : '#F5F6F7' }}>
                                <Text >{`${item}个`}</Text>
                                <IconFont style={{ marginLeft: 3 }} name="ac-jinbi2" size={35} />
                            </View>
                        )
                    })}
                </View>
                <View className="sheet-box-view">
                    <View className="btn-view" ><Button onClick={() => setShow(false)} className="btn" type='primary' plain hairline >取消</Button></View>
                    <View className="btn-view"><Button className="btn" type='primary'>确定</Button></View>
                </View>
            </ActionSheet>
            <ActionSheet show={fractionShow} title="评分" onClose={() => setFractionShow(false)}>
                <View className="sheet-view" style={{ flexDirection: 'column' }}>
                    <View>请给应用打分</View>
                    <Rate
                        value={fractionVal}
                        allowHalf
                        voidIcon="star"
                        style={{ marginTop: 10 }}
                        voidColor="#eee"
                        onChange={(e) => {
                            setFractionVal(e.detail)
                        }}
                    />
                    {fractionVal > 0.1 ? <View className='fraction-tit'>{`当前分数：${fractionVal * 2}分`}</View> : null}
                </View>
                <View className="sheet-box-view">
                    <View className="btn-view" ><Button onClick={() => setFractionShow(false)} className="btn" type='primary' plain hairline >取消</Button></View>
                    <View className="btn-view"><Button onClick={subMitCore} className="btn" type='primary'>确定</Button></View>
                </View>
            </ActionSheet>
            <Toast_ />
        </View>
    );
}